<template>
  <div class="mt12 pb20" style="overflow-y: auto; height: calc(100% - 180px)">
    <div class="fs-14 font-600 mb12">{{ $t('goodsPublishStep3.基本信息') }}</div>
    <el-form ref="formRef" :label-width="0" :model="formData" :rules="rules">
      <div class="custom-table">
        <div class="custom-table-row">
          <div class="custom-table-label w-160 required">{{ $t('goodsPublishStep3.商品规格') }}</div>
          <div class="pb0 custom-table-value">
            <el-form-item prop="spec">
              <div>
                <div
                  class="spec-item mb12"
                  v-for="(item, index) in specList"
                  :key="item.value"
                >
                  <div class="spec-item-header flex_aic_jcsb">
                    <div class="flex_aic">
                      <div class="font-600">{{ $t('goodsPublishStep3.规格名') }}</div>
                      <div>{{ item["label" + locale] }}</div>
                      <el-radio
                        class="ml24"
                        v-model="useImageIndex"
                        :value="index"
                        size="large"
                        >{{ $t('goodsPublishStep3.设置规格图片') }}</el-radio
                      >
                    </div>
                    <div class="flex_aic">
                      <el-button type="primary" link @click="editSpec(index)"
                        >{{ $t('goodsPublishStep3.编辑') }}</el-button
                      >
                      <el-button type="primary" link @click="deleteSpec(index)"
                        >{{ $t('goodsPublishStep3.删除') }}</el-button
                      >
                    </div>
                  </div>
                  <div class="spec-item-value flex_aic mt12">
                    <div
                      class="spec-item-value-item"
                      v-for="(item, index2) in item.info"
                      :key="item.id"
                    >
                      <span>{{ item["name" + locale] }}</span>
                      <el-icon
                        size="16"
                        color="#999"
                        @click="deleteSpecValue(index, index2)"
                        ><CircleCloseFilled
                      /></el-icon>
                    </div>
                  </div>

                  <el-button
                    type="primary"
                    link
                    @click="addSpecItem(index, item)"
                    >{{ $t('goodsPublishStep3.添加规格值') }}</el-button
                  >
                </div>
                <el-button class="mt12" @click="addSpec">{{ $t('goodsPublishStep3.添加规格') }}</el-button>
              </div>
            </el-form-item>
          </div>
        </div>
      </div>
      <template v-if="specList.length > 0">
        <!-- 规格数据 -->
        <el-table :data="specDataList" border class="mt12 cover-table">
          <el-table-column :label="$t('goodsPublishStep3.序号')" type="index" width="80" />
          <el-table-column
            v-for="(item, index) in specList.filter((v) => v.info.length > 0)"
            :key="item.value"
            :label="item['label' + locale]"
          >
            <template #default="{ row }">
              {{ row[`spec_${item.value}`]?.["name" + locale] || "-" }}
            </template>
          </el-table-column>
          <!-- <el-table-column label="市场价" prop="marketPrice" width="120">
          <template #default="{ row }">
            <el-input
              v-model.number="row.marketPrice"
              placeholder="请输入"
              type="number"
            />
          </template>
        </el-table-column> -->
          <el-table-column :label="$t('goodsPublishStep3.原价')" prop="originalPrice" width="200">
            <template #default="{ row }">
              <el-input-number
                v-model="row.originalPrice"
                :placeholder="$t('goodsPublishStep3.请输入')"
                type="number"
                :min="0"
                controls-position="right"
              />
            </template>
          </el-table-column>
          <el-table-column :label="$t('goodsPublishStep3.价格')" prop="price" width="200">
            <template #header>
              {{ $t('goodsPublishStep3.价格') }}<span class="color-ff2b4e">*</span>
            </template>
            <template #default="{ row }">
              <el-input-number
                v-model="row.price"
                :placeholder="$t('goodsPublishStep3.请输入')"
                type="number"
                :min="0"
                controls-position="right"
              />
            </template>
          </el-table-column>
          <el-table-column :label="$t('goodsPublishStep3.库存')" prop="stock" width="200">
            <template #header>
              {{ $t('goodsPublishStep3.库存') }}<span class="color-ff2b4e">*</span>
            </template>
            <template #default="{ row }">
              <el-input-number
                v-model="row.stock"
                :placeholder="$t('goodsPublishStep3.请输入')"
                type="number"
                :min="0"
                controls-position="right"
              />
            </template>
          </el-table-column>
          <el-table-column :label="$t('goodsPublishStep3.货号')" prop="itemCode" width="120">
            <template #default="{ row }">
              <el-input v-model="row.itemCode" :placeholder="$t('goodsPublishStep3.请输入')" />
            </template>
          </el-table-column>
          <!-- <el-table-column label="条形码" prop="barcode" width="120">
          <template #default="{ row }">
            <el-input v-model="row.barcode" placeholder="请输入" />
          </template>
        </el-table-column> -->
          <el-table-column :label="$t('goodsPublishStep3.默认选中')" width="100">
            <template #default="{ row }">
              <el-radio v-model="flag" :value="row.id" />
            </template>
          </el-table-column>
        </el-table>

        <div class="fs-14 font-600 mt24 mb12">{{ $t('goodsPublishStep3.规格图片') }}</div>
        <div class="custom-table">
          <div
            class="custom-table-row mt12"
            v-if="
              useImageIndex >= 0 && specList[useImageIndex]?.info?.length > 0
            "
            v-for="(item, index) in specList[useImageIndex]?.info || []"
            :key="index"
          >
            <div class="custom-table-label w-160 required">
              {{ item["name" + locale] }}
            </div>
            <div class="pb0 custom-table-value">
              <uploadFile v-model="item.images" :limit="1" />
            </div>
          </div>
        </div>
      </template>

      <div class="fs-14 font-600 mt24 mb12">{{ $t('goodsPublishStep3.商品视频') }}</div>
      <div class="custom-table">
        <div class="custom-table-row">
          <div class="custom-table-label w-160">{{ $t('goodsPublishStep3.视频') }}</div>
          <div class="pb0 custom-table-value">
            <UploadVideo v-model="formData.video" />
          </div>
        </div>
      </div>

      <LangTabs class="mt24" v-model="lang" />
      <div class="fs-14 font-600 mt24 mb12">{{ $t('goodsPublishStep3.商品详情描述') }}</div>
      <EditorWang v-if="showEditorWang" v-model="formData['content' + lang]" />
      <div class="footer flex_aic_jcc">
        <el-button @click="handleBack">{{ $t('goodsPublishStep3.返回') }}</el-button>
        <el-button @click="prev">{{ $t('goodsPublishStep3.上一步') }}</el-button>
        <el-button
          type="primary"
          @click="handleRelease"
          :loading="releaseLoading"
          >{{ $t('goodsPublishStep3.发布') }}</el-button
        >
      </div>
    </el-form>

    <Dialog
      v-model="editSpecDialog"
      :title="$t('goodsPublishStep3.编辑规格')"
      width="500px"
      @confirm="handleEditSpec"
      @close="editIndex = -1"
    >
      <el-select v-model="specValue" :placeholder="$t('goodsPublishStep3.请选择规格')">
        <el-option
          v-for="item in specOptions"
          :key="item.id"
          :label="item['name' + locale]"
          :value="item.id"
          :disabled="item.disabled"
        />
      </el-select>
    </Dialog>

    <Dialog
      v-model="editSpecValueDialog"
      :title="$t('goodsPublishStep3.编辑规格值')"
      width="500px"
      @confirm="handleEditSpecValue"
      @close="editSpecValueIndex = -1"
    >
      <el-select v-model="specChildValue" :placeholder="$t('goodsPublishStep3.请选择规格值')">
        <el-option
          v-for="item in specValueOptions"
          :key="item.id"
          :label="item['name' + locale]"
          :value="item.id"
          :disabled="item.disabled"
        />
      </el-select>
    </Dialog>
  </div>
</template>

<script setup>
import { computed, ref, watch, onMounted, reactive, nextTick } from "vue";
import {
  formData,
  release,
  releaseStore,
  specList,
  useImageIndex,
  specDataList,
  releaseLoading,
  flag,
} from "../releaseStore";
import uploadFile from "@/components/uploadFile.vue";
import Dialog from "@/components/dialog.vue";
import { ElMessage } from "element-plus";
import EditorWang from "@/components/editorWang.vue";
import { useRouter } from "vue-router";
import { CircleCloseFilled } from "@element-plus/icons-vue";
import Api from "@/config/api/api";
import UploadVideo from "@/components/UploadVideo.vue";
import { useI18n } from "vue-i18n";
import i18n from "@/i18n";
import LangTabs from "@/components/langTabs.vue";

const langs = reactive(Object.keys(i18n.global.messages.value));
const router = useRouter();
const { locale, t } = useI18n();
const lang = ref(locale.value);
const showEditorWang = ref(true);

const formRef = ref(null);
const rules = {};
const editSpecDialog = ref(false);
const editIndex = ref(-1);

const specOptions = ref([]);
const specValue = ref("");
const specChildValue = ref("");
const editSpecValueDialog = ref(false);
const editSpecValueIndex = ref(-1);

const specValueOptions = ref([]);
const addSpec = () => {
  editSpecDialog.value = true;
};
const editSpec = (index) => {
  specValue.value = specList.value[index].value;
  editSpecDialog.value = true;
  editIndex.value = index;
};
const deleteSpec = (index) => {
  specList.value.splice(index, 1);
};
const addSpecItem = (index, item) => {
  specChildValue.value = "";
  editSpecValueDialog.value = true;
  editSpecValueIndex.value = index;
  getSpecValueOptions(item.value);
};
const deleteSpecValue = (index, index2) => {
  specList.value[index].info.splice(index2, 1);
};

watch(
  () => specList.value,
  (newVal) => {
    // 获取所有规格的组合
    generateSpecCombinations();
  },
  { deep: true }
);

// 生成规格组合
const generateSpecCombinations = () => {
  if (specList.value.length === 0) {
    specDataList.value = [{}];
    return;
  }

  // 提取每个规格的值
  const specs = specList.value.map((spec) => {
    return {
      label: spec.label,
      value: spec.value,
      values: spec.info,
    };
  });

  // 保存旧数据，用于保持原有输入不变
  const oldDataMap = {};
  specDataList.value.forEach((item) => {
    // 使用规格值组合作为key
    const key = specs
      .map((spec) => item[`spec_${spec.value}`]?.id || "")
      .join("_");
    oldDataMap[key] = { ...item };
  });

  // 递归生成组合
  const generateCombinations = (specIndex, currentCombination) => {
    if (specIndex >= specs.length) {
      // 已经组合到最后一个规格，生成一条数据
      const key = specs
        .map((spec) => currentCombination[`spec_${spec.value}`]?.id || "")
        .join("_");

      // 如果存在旧数据，则保留旧数据中的其他字段
      const oldData = oldDataMap[key] || {};

      return [
        {
          ...oldData,
          ...currentCombination,
          id:
            oldData.id ||
            Date.now() + Math.random().toString(36).substring(2, 8),
        },
      ];
    }

    const currentSpec = specs[specIndex];
    const combinations = [];

    // 如果当前规格没有值，跳过
    if (!currentSpec.values.length) {
      return generateCombinations(specIndex + 1, currentCombination);
    }

    // 遍历当前规格的每个值，生成组合
    for (const val of currentSpec.values) {
      const newCombination = {
        ...currentCombination,
        [`spec_${currentSpec.value}`]: val,
        [`${currentSpec.label}`]: val.name,
      };
      combinations.push(...generateCombinations(specIndex + 1, newCombination));
    }

    return combinations;
  };

  // 开始生成组合
  specDataList.value = generateCombinations(0, {});
  flag.value = specDataList.value[0].id;
};

const handleEditSpec = () => {
  const item = specOptions.value.find((item) => item.id === specValue.value);
  if (specList.value.some((item) => item.value === specValue.value)) {
    ElMessage.error(t('goodsPublishStep3.规格已存在'));
    return;
  }
  if (editIndex.value === -1) {
    const obj = {
      value: specValue.value,
      info: [],
    };
    langs.forEach((el) => {
      obj["label" + el] = item["name" + el];
    });
    specList.value.push(obj);
  } else {
    specList.value[editIndex.value].value = specValue.value;
    specList.value[editIndex.value].info = [];
    langs.forEach((el) => {
      specList.value[editIndex.value]["label" + el] = item["name" + el];
    });
  }
  editIndex.value = -1;
  editSpecDialog.value = false;
};

const handleEditSpecValue = () => {
  if (!specChildValue.value) {
    ElMessage.error(t('goodsPublishStep3.请选择规格值'));
    return;
  }
  const item = specValueOptions.value.find(
    (item) => item.id === specChildValue.value
  );
  const obj = {
    id: specChildValue.value,
  };
  langs.forEach((el) => {
    obj["name" + el] = item["name" + el];
  });
  specList.value[editSpecValueIndex.value].info.push(obj);
  editSpecValueDialog.value = false;
};

const prev = () => {
  releaseStore.step = 1;
};
const handleRelease = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      if (specList.value.length === 0) {
        ElMessage.error(t('goodsPublishStep3.请添加规格'));
        return;
      }
      if (specList.value.some((item) => item.info?.length === 0)) {
        ElMessage.error(t('goodsPublishStep3.请添加规格值'));
        return;
      }
      if (
        specList.value[useImageIndex.value]?.info.some(
          (item) => !item.images || item.images?.length === 0
        )
      ) {
        ElMessage.error(t('goodsPublishStep3.请添加规格图片'));
        return;
      }
      if (specDataList.value.some((item) => !item.price && item.price !== 0)) {
        ElMessage.error(t('goodsPublishStep3.请输入价格'));
        return;
      }
      if (specDataList.value.some((item) => !item.stock && item.stock !== 0)) {
        ElMessage.error(t('goodsPublishStep3.请输入库存'));
        return;
      }
      release(router);
    }
  });
};

const handleBack = () => {
  router.back();
};

// 获取一级规格列表
const skuSpecification_list = () => {
  Api.skuSpecification_list({
    page: 0,
    size: 9999,
  }).then((res) => {
    specOptions.value = res.data?.content || [];
  });
};

const getSpecValueOptions = (id) => {
  Api.skuSpecificationDetail_list({
    page: 0,
    size: 9999,
    specificationId: id,
  }).then((res) => {
    specValueOptions.value = res.data?.content || [];
    specValueOptions.value.forEach((item) => {
      item.disabled = specList.value.some((v) =>
        v.info.some((v2) => v2.id === item.id)
      );
    });
  });
};
onMounted(() => {
  // 初始化生成规格组合数据
  generateSpecCombinations();
  skuSpecification_list();
});

// watch(
//   () => editSpecValueDialog.value,
//   (newVal) => {
//     if (newVal) {
//       getSpecValueOptions();
//     }
//   }
// );

watch(
  () => editSpecDialog.value,
  (newVal) => {
    if (newVal) {
      specOptions.value.forEach((item) => {
        item.disabled = specList.value.some((v) => v.value === item.id);
      });
    }
  }
);

watch(
  () => lang.value,
  () => {
    showEditorWang.value = false;
    nextTick(() => {
      showEditorWang.value = true;
    });
  }
);
</script>
<style lang="scss" scoped>
.h-236 {
  height: 236px;
}

.h-35 {
  height: 35px;
}

.spec-item {
  width: 500px;
  border-bottom: 1px dotted #e6e9ee;
  padding-bottom: 10px;
  .spec-item-header {
    height: 45px;
    padding-right: 17px;
    background-color: #f3f9fe;
    padding-left: 20px;
  }

  .spec-item-value {
    flex-wrap: wrap;
    gap: 10px;
    .spec-item-value-item {
      padding: 0 20px;
      border: 1px solid #efefef;
      height: 30px;
      line-height: 30px;
      position: relative;
      .el-icon {
        position: absolute;
        right: 0;
        top: 0;
        cursor: pointer;
        display: none;
      }
      &:hover {
        .el-icon {
          display: block;
        }
      }
    }
  }
}

.footer {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  width: 100%;
  height: 60px;
  border-top: 1px solid #e6e9ee;
  background: #fff;
  background: #fff;
  box-shadow: 0 0 20px #bbbbbb26;
}
</style>
